import React from "react";
import {
  BaseListPage,
  columnRenders,
  http,
  IBaseListPageState,
  IBaseListPageProps,
  UdModal,
  UdPage,
  UdFilter,
  UdTable,
  UdPageHeader
} from "@/lib";
import { Input, message, Tabs } from "antd";
import apis from "@/apis/AboutQuota";
import udMainStore from "@/store/UdMain";
import "./style.scss";
var userInfo = JSON.parse(sessionStorage.getItem("UaaSysInfo"))?.profile;
let brandCode = userInfo.profile?.brandCode[0]
const userId = userInfo.id;
const { TabPane } = Tabs;
class List extends BaseListPage<
  IQuotaAssessYearListProps,
  IQuotaAssessYearListState
  > {
  protected useConditionsField = true;
  constructor(props) {
    super(props);
    this.state = {
      title: "配额申请",
      brandCode,
      queryApi: (params) => {
        let lists = { ...params }
        lists.conditions.brandCode = this.state.brandCode
        lists.conditions.userId = userId
        return http.post(apis.GetQuotaDealer, { ...lists });
      },
      rowKey: "dealerCode",
      conditions: [
        {
          label: "客户名称",
          id: "dealerName",
          render: <Input placeholder="请输入" />,
        },
      ],
      columns: [
        { title: "客户编码", dataIndex: "dealerCode" },
        { title: "客户名称", dataIndex: "dealerName" },
        {
          title: "客户类型", render: () => {
            return <span>{'经销商'}</span>
          },
        },
        {
          title: "操作",
          render: (record) => <button className={record.openApplyFor == 'Y' ? "applyBtn" : 'disApplyBtn'} onClick={() => this.openModal(record)}>配额申请</button>,
        },
      ],
      tableProps: {
        scroll: { x: true }
      },
      assessYearList: [],
      brandLists: [],
      brandshortName: [],
    };
  }
  componentDidMount() {
    this.getBrandCompanyList()
    // super.componentDidMount();
  }
  private getBrandCompanyList = () => { //销售组织简称
    http.get(apis.getUserBrands).then(res => {
      const brandCompanies = res.data.map(({ brandCode: value, brandNameShort: title }) => ({ value, title }))
      // 过滤掉头曲二曲的
      const hideArr = ['头曲', '二曲', '泸州老窖头曲酒类销售有限公司', '泸州老窖二曲酒类销售有限公司']
      let brandfilter = brandCompanies.filter(item => hideArr.indexOf(item.title) === -1)
      this.setState({
        brandshortName: brandfilter,
        brandCode:res.data[0].brandCode
      })
    }).then(res=>{
      super.componentDidMount();
    })
  }
  render() {
    const { conditions } = this.state
    return <UdPage className="list-page">
      {
        this.state.title && <UdPageHeader title={this.state.title} subTitle={this.state.subTitle}
          affixProps={{ target: () => this.pageContainer }} />
      }
      <UdFilter
        loading={this.state.querying} items={conditions}
        getForm={(form) => { this.filterForm = form }}
        onSearch={this.handleSearch} resetAfter={this.filterReset}
      ></UdFilter>
      <Tabs defaultActiveKey={this.state.brandCode} onChange={this.switchTodoTabHandle} type="card">
        {this.state.brandshortName?.map(todoTab => (
          <TabPane tab={todoTab.title} key={todoTab.value} />
        ))}
      </Tabs>
      <UdTable loading={this.state.querying} rowKey={this.state.rowKey}
        pagination={this.state.pagination} {...this.state.tableProps}
        columns={this.state.columns} dataSource={this.state.dataSource}
        onChange={this.handleTableChange}
      />
    </UdPage>
  }
  /* 品牌切换 */
  private switchTodoTabHandle = (key) => {
    this.queryParams.page = 1 // 重置分页
    this.setState({ brandCode: key }, () => {
      this.query()
    })

  }
  //查看详情
  public goStockCheck = () => {
    if (!arr.length) {
      message.warning("请至少选择一个物料!")
      return
    } else {
      sessionStorage.setItem('brandCode', this.state.brandCode)
      this.props.history.push({
        pathname: `/quota/qoutaapplyfor/apply`,
      });
    }
  };
  public getQuotaList() {
    const productGroup = JSON.parse(sessionStorage.getItem("productGroup"))
    const dealerCode = JSON.parse(sessionStorage.getItem("dealerCode"))
    let productGroupIdList = []
    if (productGroup.length) {
      productGroup.forEach(item => {
        productGroupIdList.push(item.id)
      })
    } http.get(apis.GetProductGroupByDealer, {
      params: { brandCode: this.state.brandCode, dealerCode: dealerCode, productGroupIdList: productGroupIdList.join(',') },
    }).then(res => {
      let list = []
      res.data.quotaApplyDetailResps.forEach(item => {
        if (item.checkStockDataStatus != 'Y') {
          list.push({
            name: item.groupName,
            id: item.productGroupId
          })
        }
      })
      if (list.length) {
        UdModal.open({
          title: "提示",
          content: <div>
            {list.map(item => (
              <span key={item.id}>{item.name}</span>
            ))}
            <span>没有盘点，是否继续进行申请操作？</span>
          </div>,
          onOk: () => {
            this.goStockCheck();
          },
        });
      } else {
        this.goStockCheck();
      }
    })
  }
  public openModal = (row?) => {
    if (row.openApplyFor == 'Y') {
      var brandLists = [];
      arr = []
      sessionStorage.removeItem('productGroup')
      http.get(apis.GetProductGroupInfo, { params: { dealerCode: row.dealerCode, brandCode: this.state.brandCode } }).then((res) => {
        res.data.forEach(item => {
          item.checked = false
        })
        brandLists = res.data
        if (res.data.length) {
          UdModal.open({
            title: "请选择配额物料分类",
            content: <ComponyList dealerCode={row.dealerCode} brandLists={brandLists} />,
            onOk: () => {
              this.getQuotaList()
            },
          });
        }
      });
    } else {
      return
    }
  }
}
var arr = []
function checkValue(item) {
  item.checked = !item.checked
  let flag = arr.some(items => {
    return items.id == item.id
  })
  if (item.checked) {
    arr.push(item)
  } else if (flag) {
    arr.forEach((i, idx) => {
      if (i.id == item.id) {
        arr.splice(idx, 1)
      }
    })
  }
  sessionStorage.setItem('productGroup', JSON.stringify(arr))
}
const ComponyList = (props) => {
  let { dealerCode, brandLists } = props;
  sessionStorage.setItem('dealerCode', JSON.stringify(dealerCode))
  return (
    <div>
      {brandLists.map((item, index) => (
        <form key={item.id}>
          <label className="brandItem">
            <input className="checkSure" type="checkbox" defaultChecked={item.checked} onChange={() => checkValue(item)} />{" "}
            <span>
              {item.name}
            </span>
          </label>
        </form>
      ))}
    </div>
  );
};
export default List;

interface IQuotaAssessYearListState extends IBaseListPageState {
  assessYearList: any[];
  brandLists: any[];
  brandshortName: any[],
  brandCode: any
}

interface IQuotaAssessYearListProps extends IBaseListPageProps { }
